################################################################################
__author__ = 'Ong Zhi Xian'

################################################################################

#from webpages.admin.tools import keygen
__all__ = ['login', 'logout',
           'portfolio', 'admin']

################################################################################
import cherrypy
import os
import webpages
from mako.lookup import TemplateLookup


################################################################################
MAKO_TEMPLATES_DIRECTORY = os.path.join(os.getcwd(), 'mako')


################################################################################
lookup = TemplateLookup(directories=[MAKO_TEMPLATES_DIRECTORY])

################################################################################
# Mako templates related functions

def get_template(template_name):
    """Get returns a Mako template given a template name"""

    #cherrypy.session[SESSION_USERNAME] = '';
    #x = cherrypy.session.get(SESSION_USERNAME)
    #if x is None:
    #    cherrypy.InternalRedirect("/login")
    #    cherrypy.log(" x is none")
    #else:
    #    cherrypy.log(str(x))

    #cherrypy.log(name)
    if not template_name.lower().endswith('.html'):
        template_name = '{0}.html'.format(template_name)
    tmpl = lookup.get_template(template_name)
    return tmpl

def get_menuitems(name):
    pass

#----------------------------------------

def page_context_menu():
    pass

def get_page_menuitems():
    # read sitemaps.xml markup
    import os
    import xml.etree.ElementTree as xml
    #sitemaps_filepath = os.path.join(os.getcwd(), 'data/configuration/sitemaps.xml')
    #sitemaps_filehandler = open(sitemaps_filepath)
    #sitemaps_markup = sitemaps_filehandler.read()
    #sitemaps_filehandler.close()
    #root = xml.fromstring(sitemaps_markup)

    # Get CherryPy configuration for sitemaps
    app = cherrypy.tree.apps['/cherrybank']
    sitemaps_filepath = app.config['Sitemap']['filepath']
    sitemap_id = app.config['Sitemap']['id']
    cherrypy.log('sitemaps_filepath: {0}'.format(sitemaps_filepath))
    cherrypy.log('sitemap_id: {0}'.format(sitemap_id))

    tree = xml.parse(sitemaps_filepath)
    root = tree.getroot()

    locations = root.findall('./map[@id="{0}"]/'.format(sitemap_id))
    cherrypy.log('./map[@id="{0}"]/'.format(sitemap_id))
    cherrypy.log(str(len(locations)))
    for location in locations:
        location.set('url',  webpages.PageHelper.get_url(location.get('url')))
    return locations
    #clt = MongoClient(database_server, database_port)

    pass

def page_output(template_name, ctx):
    import tools

    username = cherrypy.request.login

    cherrypy.log('template_name: {0}'.format(template_name))
    if template_name.lower() == 'webpages.logout':
        username = None

    tmpl = get_template(template_name)
    #m = MenuHelper.get_menuitems()

    if username is None:
        menuitems = []
        logout_link = None
        login_link = { 'href': webpages.PageHelper.get_url('/login'),   'text': 'Login'}
    else:
        #menuitems = [
        #    { 'href': webpages.PageHelper.get_url('/account'),   'text': 'Account'}
        #    ]
        menuitems = get_page_menuitems()
        logout_link = { 'href': webpages.PageHelper.get_url('/logout'),   'text': 'Logout'}
        login_link = None

    if ctx is None or type(ctx) is not dict:
        ctx = {
            'menuitems': menuitems,
            'logout_link': logout_link,
            'login_link': login_link
        }
    else: # ctx is a dictionary passed from user; merge menuitems into dictionary
        ctx['menuitems'] = menuitems
        ctx['logout_link'] = logout_link
        ctx['login_link'] =  login_link

    #cherrypy.log(str(ctx.keys()))
    #tmpl = webpages.get_template(__name__)
    #cherrypy.log(str(dir(tmpl)))
    #cherrypy.log(help(tmpl.render))
    #return tmpl.render(salutation="Hello", target="World")
    return tmpl.render(ctx=ctx)
    app = cherrypy.tree.apps['']
    database_server = app.config['MongoDB']['database_server']
    database_port = app.config['MongoDB']['database_port']
    database_name = app.config['MongoDB']['database_name']


class PageHelper(object):
    @staticmethod
    def get_url(url):
        return str.format('{0}{1}{2}', cherrypy.request.base, cherrypy.request.script_name, url)
        #return cherrypy.request.base + url